/**      
 * 对Date的扩展，将 Date 转化为指定格式的String      
 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符      
 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)      
 * eg:      
 * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423      
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04      
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04      
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04      
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18      
 */        
Date.prototype.pattern=function(fmt) {         
    var o = {         
    "M+" : this.getMonth()+1, //月份         
    "d+" : this.getDate(), //日         
    "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时         
    "H+" : this.getHours(), //小时         
    "m+" : this.getMinutes(), //分         
    "s+" : this.getSeconds(), //秒         
    "q+" : Math.floor((this.getMonth()+3)/3), //季度         
    "S" : this.getMilliseconds() //毫秒         
    };         
    var week = {         
    "0" : "/u65e5",         
    "1" : "/u4e00",         
    "2" : "/u4e8c",         
    "3" : "/u4e09",         
    "4" : "/u56db",         
    "5" : "/u4e94",         
    "6" : "/u516d"        
    };         
    if(/(y+)/.test(fmt)){         
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));         
    }         
    if(/(E+)/.test(fmt)){         
        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);         
    }         
    for(var k in o){         
        if(new RegExp("("+ k +")").test(fmt)){         
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));         
        }         
    }         
    return fmt;         
} 

function Map(){
	this.data = new Object();
	this.length = 0;
 }
Map.prototype.put = function(key,value){
	this.data[key] = value;
	this.length++;
};

Map.prototype.get = function(key){
	return this.data[key];
};

Map.prototype.remove = function(key){
	this.data[key] = null;
	this.length--;
};
	  
Map.prototype.isEmpty = function(){
	return this.length == 0;
};

Map.prototype.size = function(){
	return this.length;
};
Map.prototype.keySet = function() {
	return this.data;
}

Array.prototype.remove = function(dx) 
{ 
    if(isNaN(dx)||dx>this.length){return false;} 
    for(var i=0,n=0;i<this.length;i++) 
    { 
        if(this[i]!=this[dx]) { 
            this[n++]=this[i] 
        }
    } 
    this.length-=1;
}

var utils = {
	getSpriteAvatarClass : function(o) {
		// alert(o.attr('class'));
		var obj = o.attr('class').split(' ');
		for (var i = 0; i < obj.length; i++) {
			if (obj[i].indexOf('sprite-Avatar') != -1)
				return obj[i];
		}
	},
	getAvatarColorClass : function(color, size) {
		return "sprite-Avatar-Base-" + color + "-" + size + "_2x";
	},
	getAvatarIconClass : function(icon, size) {
		return "sprite-Avatar-Icon-" + icon + "-" + size + "_2x";
	},
	getAvatarColor : function(colorClass) {
		return colorClass.split('-')[3];
	},
	getAvatarIcon : function(iconClass) {
		return iconClass.split('-')[3];
	},
	updateAvatarClass : function(avatar, newAvatarClass) {
		var avatarClass = utils.getSpriteAvatarClass(avatar);
		avatar.removeClass(avatarClass);
		avatar.addClass(newAvatarClass);
	},
	removeElement : function(_element) {
		var _parentElement = _element.parentNode;
		if (_parentElement) {
			_parentElement.removeChild(_element);
		}
	},
	removeArrElement : function(arr, elementKey, elementValue, compareFun) {
	   // if(isNaN(dx)||dx>this.length){return false;} 
		if (compareFun == 1) {    //通过index来定位需要移除的元素
			compareFun = function(elem, index, key, value) {
				return index != key;
			}
		} else if (compareFun == 2) {  //通过元素中某个属性值来定位需要移除的元素
			compareFun = function(elem, index, key, value) {
				return elem[key] != value;
			}
		}
		for(var i=0,n=0;i < arr.length;i++) 
		  { 
			  if(compareFun(arr[i], i, elementKey, elementValue)) { 
				  arr[n++]=arr[i];
			  }
		  } 
		arr.length -= 1;
	},
	getArrElement: function(arr, key, value) {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i][key] == value) {
				return arr[i];
			}
		}
	},
	toJSONObject: function(jsonString) {
		return JSON.parse(jsonString);
	},
	toJSONString: function(jsonObject) {
		return JSON.stringify(jsonObject);
	}
};
$(function () {
	
	var pageInit = {};
	pageInit.initFun = [];
	pageInit.addInitFun = function(fun) {
		this.initFun.push(fun);
	}
	pageInit.init = function() {
		for (var i = 0; i < this.initFun.length; i++) {
			this.initFun[i]();
		}
	};
	
	if (!window.WebSocket && window.MozWebSocket)
		window.WebSocket=window.MozWebSocket;
	if (!window.WebSocket)
		alert("此浏览器不支持WebSocket");
	
	var MessageType = {};
	MessageType.TEXT_MSG = 1;
	MessageType.IMAGE_MSG = 2;
	MessageType.LOGIN_STATUS = 3;
	MessageType.ONLINE_USER_NUM = 4;
	MessageType.USER_MATCH = 5;
	MessageType.REMOVE_CONVO = 6;
	MessageType.ADD_FRIEND_REQUEST = 7;
	MessageType.ADD_FRIEND_REQUEST_STATUS = 8;
	var ws = {};
	function webSocketInit() {
		ws = new WebSocket("ws://" + location.host + "/ws/chat/" + profile.id);
		ws.onopen = function(event) {
			console.log('connection successful');
		}
		ws.onclose = function(event) {
			console.log(event);
		}
		ws.onerror = function(event) {
			console.log(event);
		}
		
		ws.onmessage = function(event) {
			var msg = JSON.parse(event.data);
			switch (msg.msgType) {
			case MessageType.TEXT_MSG:
			case MessageType.IMAGE_MSG:
				chatSection.newMessageEvent(msg);
				chatSection.updateUnreadMessages(msg.sessionId);
				break;
			case MessageType.LOGIN_STATUS:
				chatSection.updatePartnerStatus(msg);
				break;
			case MessageType.ONLINE_USER_NUM:
				rightDiv.updateOnlineUserCount(msg.content);
				break;
			case MessageType.USER_MATCH:
				chatSection.newConvoEvent(utils.toJSONObject(msg.content), msg.sessionId);
				break;
			case MessageType.REMOVE_CONVO:
				var convoId = msg.content;
				if (chatSection.selectedConvo.id == convoId) {
					rightDiv.overChatFlag = 1;
					rightDiv.overChat();
				} else {
					var res = chatSection.findConvoAndIndex("id", convoId);
					res.convo.type = Convo.prototype.TYPE_OVER;
					var lastMessageWrapper = $('#' + convoId).find('.last_message_wrapper');
					//console.log(lastMessageWrapper.width());
					lastMessageWrapper.removeClass('mw-right-last mw-left-last');
					lastMessageWrapper.find('.last_message').text('对方已结束聊天');
				}
				break;
			case MessageType.ADD_FRIEND_REQUEST:
				chatSection.newMessageEvent(msg);
				chatSection.updateUnreadMessages(msg.sessionId);
				break;
			case MessageType.ADD_FRIEND_REQUEST_STATUS:
				chatSection.newMessageEvent(msg);
				//chatSection.updateUnreadMessages(msg.sessionId);
				break;
			default:
				break;
			}
		}
	}
	function showErrorInfo(field, error) {
		field.val('');
		field.focusout();
		field.addClass('red');
		field.attr("placeholder", error);
	}
	var profile = {};
	userManage.getUserInfo(function(data) {
		profile = data;
		if (!profile.interests) {
			profile.interests = '';
			profile.interestsArr = [];
		}
		editProfile.interestsTagNum = profile.interestsArr.length;
		//profile.$dwrClassName = 'UserInfo';
		webSocketInit();
		console.log(profile);
		if (profile.registered == 0) {
			var createAccountModal = $('#create-account-modal').modal('hide');
			$('#create_div_wrapper').on('click', function() {
				$('.overlay').show();
			});
			createAccountModal.on('hide.bs.modal', function() {
				$('.overlay').hide();
			});
			
			$('#modal-create-account-button').click(function() {
				var emailField = $('#modal-email-chat');
				var passField = $('#modal-pass-chat');
				var emailReg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
				if (emailField.val().length == 0 || !emailReg.test(emailField.val())) {
					showErrorInfo(emailField, "请输入一个有效的邮箱");
					return;
				}
				if (passField.val().length < 6) {
					showErrorInfo(passField, "密码长度必须大于或等于6");
					return;
				}
				userManage.userRegister(profile.id, profile.userName, emailField.val(), passField.val(), function(res) {
					if (res == 0) {
						showErrorInfo(emailField, "邮箱已被使用");
					} else {
						location.reload();
					}
				});
			});
		}
		if (profile.registered == 1) {
			$('#dropdown-edit-username').click(function(){
				showEditUsernameModal();
			});
			$('#edit-username-btn-wrapper').click(function() {
				var editUsernameField = $('#edit-username-input');
				var editUserError = $('#edit-user-error');
				if (editUsernameField.val().length == 0) {
					editUserError.text('无效的用户名');
					return;
				}
				userManage.editUsername(profile.id, editUsernameField.val(), function(res) {
					if (res == 0) {
						editUserError.text('用户名已经被使用');
					} else {
						editUserError.text('');
						profile.userName = editUsernameField.val();
						$('#edit-username-modal').modal('hide');
						$('#left_profile_username').text('@' + profile.userName);
					}
				}); 
			});
			$('#edit-username-input').on('keydown', function(e) {
				if (e.which == 13) {
					$('#edit-username-sure').click();
				}
				return true;
			});
			
			$('#dropdown-reset-password').click(function() {
				$('.overlay').show();
				$('#reset-password-modal').modal('show');
			});
			$('#modal-reset-button-button').click(function() {
				var newPass = $('#new-password-input');
				var verify = $('#verify-password-input');
				
				if (newPass.val().length < 6) {
					showErrorInfo(newPass, '密码长度要大于或等于6');
					return;
				}
				if (newPass.val() != verify.val()) {
					showErrorInfo(verify, '密码不匹配');
					return;
				}
				userManage.editPassword(profile.id, newPass.val(), function() {
					$('#reset-password-modal').modal('hide');
				});
			});
			$('#new-password-input, #verify-password-input').on('keydown', function(e) {
				if (e.which == 13) {
					$('#modal-reset-button-button').click();
				}
			});
		}
	});
	
	$('#reset-password-modal').on('hide.bs.modal', function() {
		$('#new-password-input').val('');
		$('#verify-password-input').val('');
		$('.overlay').hide();
	});
	
	function showEditUsernameModal() {
		$('.overlay').show();
		$('#edit-username-input').val(profile.userName);
		$('#edit-username-modal').modal('show');
	}
	
	$('#edit-username-modal').on('hide.bs.modal', function() {
		$('#edit-username-error').text('');
		$('.overlay').hide();
	});
	
	
	//调整聊天区域的top值
	function divChatAreaTopAdjust() {
		var partner_business_card = $("#partner-business-card");
		var chat_area_wrapper = $('#chat-area-wrapper');
		if (!partner_business_card.is(':hidden')) {
			var height = partner_business_card.outerHeight(true);
			chat_area_wrapper.css('top', 70 + height);
		} else {
			chat_area_wrapper.css('top', 70); 
		}
	}
	divChatAreaTopAdjust();
	
	$('#partner-name-view').click(function() {
		var partner_business_card = $("#partner-business-card");
		partner_business_card.toggle(0, function() {
			divChatAreaTopAdjust();
		});
	});
	
	//调整每一个聊天会话的div宽度
	function adjustPartnerRightDivWidth(convoId) {
		convoId = convoId ? '#' + convoId + ' ' : ''; 
		var partner_right = $(convoId + '.partnerRight');
		var totalWidth = $('#conversation-sidebar').width();
		var leftWidth = 51;
		var scrollWidth = totalWidth - $('#conversation-list-wrapper').width(); //获取滚动条的宽度
		try {
			partner_right.css('width', (totalWidth - leftWidth - 20 - scrollWidth) + 'px');
			$('.partnerRightFreechat').css('width', (totalWidth - leftWidth - 15 - scrollWidth) + 'px');
		} catch(e) {
			alert(e);
		}
	}
	//adjustPartnerRightDivWidth();
	setTimeout(adjustPartnerRightDivWidth, 10);  //延时刷新聊天会话div的宽度，解决在页面初始化时不能获取滚动条宽度的问题
	
	//调整聊天会话列表的高度为整个页面剩余的高度
	function adjustConversationSidebarHeight() {
		var bodyHeight = $('body').outerHeight(true);
		var newButtonWrapperH = $('#new-button-wrapper').outerHeight(true);
		var left_profile_wrapperH = $('#left_profile_wrapper').outerHeight(true);
		var global_search_wrapper_H = $('#global_search').outerHeight(true);
		var convo_sorter_H = $('#convo-sorter').outerHeight(true);
		$('#middle_wrapper').height(bodyHeight);
		$('#conversation-sidebar').height(bodyHeight - newButtonWrapperH - 
				left_profile_wrapperH - global_search_wrapper_H - convo_sorter_H - 5);
		
	}
	//adjustConversationSidebarHeight();
	
	var windowResize = {};    //用于注册当浏览器窗口被手动调整时执行的函数
	windowResize.resizeFun = [];
	windowResize.resize = function() {
		for (var i = 0; i < this.resizeFun.length; i++) {
			this.resizeFun[i]();
		}
	}
	windowResize.add = function(fun) {
		this.resizeFun.push(fun);
	}
	windowResize.add(adjustPartnerRightDivWidth);
	windowResize.add(adjustConversationSidebarHeight);
	
//	构造函数原型混合模式 
//	function Person(name, age, job) { 
//	this.name = name; 
//	this.age = age; 
//	this.job = job; 
//	} 
//
//	Person.prototype.sayName = function () { 
//	alert(this.name); 
//	}
	
	/**
	 * type: 0:waiting,1:normal,2:friend, 3:team
	 * status: 0:offline, 1:online, 2:waiting
	 */
//	function Convo(id, type, status, nickName, avatarColor, avatarIcon,
//			introduction, gender, age, location, interests) {
//		this.id = id;
//		this.type = type;
//		this.status = status;
//		this.nickName = nickName;
//		this.avatarColor = avatarColor;
//		this.avatarIcon = avatarIcon;
//		this.introduction = introduction;
//		this.gender = gender;
//		this.age = age;
//		this.location = location;
//		this.interests = interests;
//	}
	function Convo(id, type, userId) {
		this.id = id;
		this.type = type;
		this.userId = userId;
	}
	Convo.prototype.TYPE_WAITING = 0;
	Convo.prototype.TYPE_NORMAL = 1;
	Convo.prototype.TYPE_FRIEND = 2;
	Convo.prototype.TYPE_OVER = 3;
	//Convo.prototype.TYPE_TEAM = 3;
	Convo.prototype.getId = function() {
		return this.id;
	}
	Convo.prototype.getType = function(str) { //str参数代表是否要获取字符串形式的会话类型
		if (str) {
			if (this.type == 0) {
				str = 'waiting';
			} else if (this.type == 1) {
				str = 'normal';
			} else if (this.type == 2) {
				str = 'friend';
			} else if (this.type == 3) {
				str = 'team';
			}
			return str;
		}
		return this.type;
	}
	
	var chatSection = {};
	chatSection.allConvos = {};
	chatSessionManage.getAllConvos(function(data) {
		chatSection.allConvos = data;
		//console.log(data);
		var selectedConvoDiv = $('#conversation-list .selected-convo');
		var res = chatSection.findConvoAndIndex("type", Convo.prototype.TYPE_WAITING);
		var waitingConvo = res.convo;
		if (waitingConvo && selectedConvoDiv.attr('id') == waitingConvo.id) {
			selectedConvoDiv = selectedConvoDiv.next();
		}
		selectedConvoDiv.click();
		if (waitingConvo) {
			chatSection.hasWaitingConvo = true;
			//console.log(waitingConvo);
			chatSessionManage.startMatch(waitingConvo.userId, waitingConvo.id);
		}
	});
	chatSection.selectedConvo = {};
	chatSection.hasWaitingConvo = false;
	chatSection.showConvos = function(sort) {
		for (var i = 0; i < this.allConvos.length; i++) {
			var convo = this.allConvos[i];
			var convoDiv = $('#' + convo.id);
			convoDiv.hide();
			if (sort == 'all-sort') {
				convoDiv.show();
			} else if (sort == 'friends-sort' && convo.type == Convo.prototype.TYPE_FRIEND) {
				convoDiv.show(); 
			} else if (sort == 'online-sort' && convo.type != Convo.prototype.TYPE_WAITING && convo.partner.logined == 1) {
				convoDiv.show();
			}
		}
	}
	chatSection.showSearchDiv = function(content) {
		function listName(pre, text) {
			return $('<span class="list_name"></span>').append(pre).append($('<span class="search-text-element"></span>').text(text));
		}
		function searchDiv(id, pre, text) {
			var div = $('<li class="convo-div search-div disconnected-name" id="' + id + '"></li>');
			div.append(listName(pre, text));
			div.click(function() {
				if (id == 'search-add-by-username') {
					var username = text.substring(1);
					if (username == profile.userName)
						return;
					chatSessionManage.searchAddByUsername(profile.id, username, function(resJSON) {
						//console.log(resJSON);
						var res = utils.toJSONObject(resJSON);
						var resCode = res.resultCode;
						var data = res.data;
						if (resCode == 0) {
							return;
						} else if (resCode == 1) {
							var convoDiv = $('#' + data);
							if (!convoDiv)
								return;
							var globalSearch = $('#global_search');
							globalSearch.val('');
							globalSearchInputChange(globalSearch);
							chatSection.switchConvo(convoDiv);
						} else {
							chatSection.newConvoEvent(data, null);
						}
					});
				}
			});
			return div;
		}
		//prepend(searchDiv('search-add-tag', '开始关于', '#' + content))
		$('#conversation-list').prepend(
				searchDiv('search-add-by-username', '通过用户名添加', '@' + content));
	}
	chatSection.removeSearchDiv = function() {
		if ($('#search-add-tag')) {
			$('#search-add-tag').remove();
		}
		if ($('#search-add-by-username')) {
			$('#search-add-by-username').remove();
		}
	}
	chatSection.switchConvo = function(selectedConvoDiv) {
		$('.convo-div').removeClass('selected-convo');
		selectedConvoDiv.addClass('selected-convo');
		this.selectedConvo = utils.getArrElement(chatSection.allConvos, 'id', selectedConvoDiv.attr('id'));
		//console.log(this.selectedConvo);
		this.clearUnreadMessages(selectedConvoDiv);
		rightDiv.showRight(selectedConvoDiv.attr('id'));
	}
	chatSection.removeConvo = function(convoDiv, autoSwitch) {
		var nextConvo = convoDiv.next();
		if (nextConvo.length == 0)
			nextConvo = convoDiv.prev();
		convoDiv.remove();
		var convo = this.findConvoAndIndex("id", convoDiv.attr('id')).convo;
		console.log("removeConvo:" + convo);
		if (convo.type == Convo.prototype.TYPE_FRIEND) {
			this.updateConvosNum("friends", -1);
		}
		if (convo.partnerStatus == 1) {
			this.updateConvosNum("online", -1);
		}
		this.updateConvosNum("all", -1);
		utils.removeArrElement(chatSection.allConvos, 'id', convo.id, 2);  //郁闷了。。传参出错了
		if (autoSwitch && this.selectedConvo.id == convo.id)
			this.switchConvo(nextConvo);
	}
	chatSection.moveConvoToFirst = function(convoDiv) {
		if (convoDiv.index() == 0)
			return;
		//console.log("fef");
		var convoClone = convoDiv.clone(true);
		convoDiv.remove();
		$('#conversation-list').prepend(convoClone);
		$('#conversation-sidebar').scrollTop(0);
	}
	chatSection.clearUnreadMessages = function(selectedConvoDiv) {
		if (this.selectedConvo.type == Convo.prototype.TYPE_WAITING)
			return;
		selectedConvoDiv.find('.unread-messages').text('');
		//console.log(this.selectedConvo);
		chatSessionManage.clearUnreadMessages(this.selectedConvo.id, this.selectedConvo.userId);
	}
	chatSection.newMessageEvent = function(msg) {
		var convo = utils.getArrElement(this.allConvos, "id", msg.sessionId);
		if (msg.msgType == MessageType.ADD_FRIEND_REQUEST) {
			if (chatSection.selectedConvo.id == convo.id)
				$('#friendRequest').show();
			convo.friendRequestSender = msg.senderId;
			this.moveConvoToFirst($('#' + convo.id));
			//chatSection.updateUnreadMessages(msg.sessionId);
			return;
		} else if (msg.msgType == MessageType.ADD_FRIEND_REQUEST_STATUS) {
			if (msg.content == '0') {
				convo.friendRequestSender = null;
				$('#add-friend-button .label-icon').text('添加朋友');
				rightDiv.addFriendRequestResultDiv(msg);
			} else {
				this.acceptFriend(convo);
				rightDiv.addFriendRequestResultDiv(msg);
			}
		} else if (msg.msgType ==  MessageType.TEXT_MSG || msg.msgType == MessageType.IMAGE_MSG) {
			rightDiv.addMessageDiv($('#chat-area'), msg);
			this.updateLastMessage(msg, convo);
			//chatSection.updateUnreadMessages(msg.sessionId);
			this.moveConvoToFirst($('#' + convo.id));
		}
		this.addMessage(msg, convo);
		$('#chat-area-wrapper').scrollTop($('#chat-area').height());
	}
	chatSection.updateConvosNum = function(sortWay, update) {
		var numSpan = $("#" + sortWay + "-sort span");
		var onlineNum = parseInt(numSpan.text()) + update;
		numSpan.text(onlineNum);
	}
	chatSection.addMessage = function(message, convo) {
		var convo = convo || utils.getArrElement(this.allConvos, "id", message.sessionId);
		if (!convo.messages)
			convo.messages = [];
		convo.messages.push(message);
	}
	chatSection.updateUnreadMessages = function(convoId, convoDiv) {
		convoDiv = convoDiv || $('#' + convoId);
		if (convoId == this.selectedConvo.id)
			return;
		chatSessionManage.addUnreadMessage(convoId, profile.id);
		var unreadMsgsDiv = convoDiv.find('.unread-messages');
		var count = parseInt(unreadMsgsDiv.text());
		if (!count)
			count = 0;
		count++;
		unreadMsgsDiv.text(count + '');
	}
	chatSection.updateLastMessage = function(message, convo) {
		convo = convo || utils.getArrElement(this.allConvos, "id", message.sessionId);
		convo.lastMessage = message;
		var convoDiv = $('#' + convo.id);
		convoDiv.find('.last_timestamp').text(message.sendTime.substring("yyy-mm-dd ".length));
		var content = "";
		if (message.msgType == MessageType.TEXT_MSG)
			content = message.content;
		var last_message_wrapper = convoDiv.find('.last_message_wrapper');
		if (message.senderId != profile.id) {  //left
			if (message.msgType == MessageType.IMAGE_MSG)
				content = "接收到一张图片";
			last_message_wrapper.removeClass('mw-right-last').addClass('mw-left-last');
		} else {    //right
			if (message.msgType == MessageType.IMAGE_MSG)
				content = "你发送了一张图片";
			last_message_wrapper.removeClass('mw-left-last').addClass('mw-right-last');
		}
		convoDiv.find('.last_message').text(content);
	}
	chatSection.updatePartnerStatus = function(msg) {
		var statusSpan = $('#conversation-list #' + msg.sessionId).find('.status');
		var convo = this.findConvoAndIndex("id", msg.sessionId).convo;
		console.log(convo);
		if (msg.content == '0') {
			convo.partnerStatus = 0;
			statusSpan.removeClass('online').addClass('offline');
			this.updateConvosNum("online", -1);
		} else {
			convo.partnerStatus = 1;
			statusSpan.removeClass('offline').addClass('online');
			this.updateConvosNum("online", 1);
		}
	}
	chatSection.createNewWaitingDiv = function() {
		if (this.hasWaitingConvo) {
			return;
		}
		this.hasWaitingConvo = true;
		var waitingDiv = $('<li class="convo-div waiting-div disconnected-name"></li>');
		waitingDiv.append($('<span class="list_name"></span>').text("等待..."));
		var waitingObj = new Convo(Math.uuid(), Convo.prototype.TYPE_WAITING, profile.id);
		waitingObj.createTime = new Date().pattern("yyyy-MM-dd HH:mm:ss");
		this.allConvos.push(waitingObj);
		waitingDiv.attr("id", waitingObj.id);
		waitingDiv.click(function() {
			chatSection.switchConvo($(this));
		});
		$('#conversation-list').prepend(waitingDiv);
		this.updateConvosNum("all", 1);
		waitingDiv.click();
		chatSessionManage.addNewConvo(waitingObj);
	}
	chatSection.createNewConvoDiv = function(waitingDiv, convo) {
		//console.log(convo);
		//var convoDiv = $("<li class='convo-div conversation'><li>");
		var convoDiv;
		if (waitingDiv) {
			waitingDiv.unbind();
			convoDiv = waitingDiv.removeClass('waiying-div disconnected-name').addClass('conversation');
		} else {
			convoDiv = $("<li class='convo-div conversation'></li>");
			$('#conversation-list').prepend(convoDiv);
		}
		
		convoDiv.addClass(convo.type == Convo.prototype.TYPE_NORMAL ? 'normal' : 'friends');
		convoDiv.attr('id', convo.id);
		convoDiv.empty();
		convoDiv.click(function() {
			chatSection.switchConvo($(this));
		});
		
		var partnerAvatarSmallDiv = "<div class='partnerAvatarSmall'>" +
				"<div class='partnerAvatarColorSmall avatar-sprite sprite-Avatar-Base-" + convo.partner.avatarColor + "-42_2x'></div>" +
				"<div class='partnerAvatarIconSmall avatar-sprite sprite-Avatar-Icon-" + convo.partner.avatarIcon + "-42_2x'></div>" +
				"</div>";
		convoDiv.append(partnerAvatarSmallDiv);
		if (convo.type == Convo.prototype.TYPE_FRIEND) {
			convoDiv.append("<div class='conversationStar'></div>");
		}
		var partnerRight = $("<div class='partnerRight'></div>");
		var nickNameSpan = $("<span class='list_name' id='name_"+ convo.id + "'>" +
							convo.partnerNickName +
						"</span>");
		if (convo.type == Convo.prototype.TYPE_FRIEND) {
			nickNameSpan.attr('title', '双击编辑');
			nickNameSpan.dblclick(function() {
				chatSection.editFriendsNickName($(this));
			});
		}
		partnerRight.append(nickNameSpan);
		var statusSpan = "<span class='status " + (convo.partnerStatus == 0 ? "offline" : "online") + "'></span>";
		partnerRight.append(statusSpan);
		if (convo.partnerStatus == 1) {
			this.updateConvosNum("online", 1);
		}
		partnerRight.append("<span class='last_timestamp'>" +
					(convo.lastMsgTime ? convo.lastMsgTime : "") +
				"</span>");
		partnerRight.append("<span class='unread-messages'>" +
					(convo.unreadMessages == 0 ? "" : convo.unreadMessages) +
				"</span>");
		var lastMessageWrapper = "";
		if (convo.lastMessage) {
			lastMessageWrapper = 
				"<div class='last_message_wrapper "+ 
			(convo.userId == convo.lastMessage.senderId ? "mw-right-last" : "mw-left-last") +"'>" +
						"<div class='last_message'>" +
							convo.lastMessage.content +
						"</div>" +
					"</div>";
		} else {
			lastMessageWrapper = 
				"<div class='last_message_wrapper'>" +
					"<div class='last_message'></div>" +
				"</div>";
		}
		partnerRight.append(lastMessageWrapper);
		convoDiv.append(partnerRight);
		spriteAvatarIconLocationAdjust.partnerAvatar(convo.id);
		adjustPartnerRightDivWidth(convo.id);
		return convoDiv;
	}
	chatSection.newConvoEvent = function(convo, oldSessionId) {
		//var convo = utils.toJSONObject(convoJSON);
		var res = this.findConvoAndIndex("id", oldSessionId);
		var waiting = res.convo;
		if (waiting && waiting.type == Convo.prototype.TYPE_WAITING) {
			this.allConvos[res.index] = convo;
			//console.log(convo);
			var waitingDiv = $('#' + waiting.id);
			var convoDiv = this.createNewConvoDiv(waitingDiv, convo);
			if (this.selectedConvo.id == waiting.id) {
				this.switchConvo(convoDiv);
			}
			this.hasWaitingConvo = false;
		} else if (!waiting) {
			chatSection.updateConvosNum("all", 1);
			this.allConvos.push(convo);
			var convoDiv = this.createNewConvoDiv(null, convo);
			var globalSearch = $('#global_search');
			if (profile.id == convo.userId) {
				globalSearch.val('');
				globalSearchInputChange(globalSearch);
				this.switchConvo(convoDiv);
			}
		}
		
	}
	
	chatSection.findConvoAndIndex = function(attrName, val) {
		var result = {};
		if (val == null) {
			return result;
		}
		for (var i = 0; i < this.allConvos.length; i++) {
			if (this.allConvos[i][attrName] == val) {
				result.convo = this.allConvos[i];
				result.index = i;
				return result;
			}
		}
		return result;
	}
	chatSection.editFriendsNickName = function(nickNameSpan) {
		var friendName = nickNameSpan;
		friendName.removeAttr('title');
		var name = friendName.text();
		var nameEditForm = $('<form class="friend-list-name-edit" style="display:inline"></form>');
		nameEditForm.append($('<input width="140" height="28" autocomplete="off" maxlength="20" name="value" />').val(name));
		function editSuccess(form, newName) {
			if(newName.length != 0) {
				name = newName;
			}
			form.remove();
			var convoId = friendName.closest('.convo-div').attr('id');
			profile.nickName = name;
			chatSessionManage.updateFriendNickName(convoId, profile.id, name);
			friendName.text(name);
			friendName.attr('title', '双击编辑');
			if (chatSection.selectedConvo.id == convoId) {
				$('#partner-name').text(name);
			}
		}
		nameEditForm.bind('keydown', function(e) {
			var newName = $(this).find('input').val();
			if (e.which == 13) {
				editSuccess($(this), newName);
			}
		});
		nameEditForm.bind('focusout', function() {
			var newName = $(this).find('input').val();
			editSuccess($(this), newName);
		});
		friendName.text('').append(nameEditForm);
		friendName.find('input').focus();
	}
	chatSection.acceptFriend = function(convo) {
		//var convo = this.findConvoAndIndex("id", convoId);
		convo.type = Convo.prototype.TYPE_FRIEND;
		convo.needEditPartnerNickName = true;
		if (chatSection.selectedConvo.id == convo.id) {
			$('#' + convo.id).click();
		}
		this.updateConvosNum("friends", 1);
	}
	$('.friends .list_name').dblclick(function(){
		chatSection.editFriendsNickName($(this));
	});
	
	function globalSearchInputChange(inputField) {
		var content = inputField.val();
		var patt = new RegExp('^\\s+$', "i");
		chatSection.removeSearchDiv();
		if (content.search(patt) != -1) {
			return;
		}
		chatSection.showSearchDiv(content);
		patt = new RegExp(content.trim(), "i");
		$('#conversation-list .convo-div').each(function() {
			var name = $(this).find('.list_name').text();
			if (name.search(patt) != -1 || content.length == 0) {
				$(this).show();
			} else {
				$(this).hide();
			}
		});
		if (content.length == 0) {
			chatSection.removeSearchDiv();
		}
	}
	
	$('#global_search').bind('input propertychange', function() {
		globalSearchInputChange($(this));
	}); 
	
	$('#x_discon').click(function() {
		var convo = $(this).closest('.convo-div');
		chatSection.removeConvo(convo, true);
		chatSection.hasWaitingConvo = false;
		chatSessionManage.stopMatch(profile.id, convo.attr('id'));
	});
	$('.convo-div').click(function() {
		chatSection.switchConvo($(this));
	});
	//pageInit.addInitFun(chatSection.initConvos);
	$('.sort-div').click(function() {
		$('.sort-div').removeClass('active-sort-div');
		$(this).addClass('active-sort-div');
		chatSection.showConvos($(this).attr('id'));
	});
	
	//调整所有spriteAvatarIcon在相应的div上的位置，使其位于中间
	function SpriteAvatarIconLocationAdjust() {
		var dw, dh;
		var locationAdjust = function(w1, h1, w2, h2) {
			dw = Math.abs((w1 - w2) / 2);
			dh = Math.abs((h1 - h2) / 2);
		};
		this.partnerAvatar = function(convoId) {
			convoId = convoId ? '#' + convoId + ' ' : '';
			//var partnerAvatarSmall = $('.partnerAvatarSmall').first();
			$(convoId + '.partnerAvatarSmall').each(function() {
				var partnerAvatarSmallHeight = $(this).height();
				var partnerAvatarSmallWeight = $(this).width();
				var partnerAvatarIconSmall = $(this).find('.partnerAvatarIconSmall');
				var partnerAvatarIconSmallHeight = partnerAvatarIconSmall.height();
				var partnerAvatarIconSmallWidth = partnerAvatarIconSmall.width();
				locationAdjust(partnerAvatarSmallWeight, partnerAvatarSmallHeight, 
						partnerAvatarIconSmallWidth, partnerAvatarIconSmallHeight);
				partnerAvatarIconSmall.css({
					'margin-left': dw + 'px',
					'margin-top': dh + 'px'
				});
			});
		};
		
		this.leftProfileAvatar = function() {
			var left_profile_avatar = $('#left_profile_avatar_wrapper .left_profile_avatar');
			var left_profile_avatar_h = left_profile_avatar.height();
			var left_profile_avatar_w = left_profile_avatar.width();
			locationAdjust(56,56,left_profile_avatar_w,left_profile_avatar_h);
			left_profile_avatar.css({
				'margin-left': dw + 'px',
				'margin-top': dh + 'px'
			});
		};
		
		
		this.partnerHeader = function() {
			var partnerHeaderIcon = $('#partnerHeaderAvatar .partnerHeaderIcon');
			var partnerHeaderIconHeight = partnerHeaderIcon.height();
			var partnerHeaderIconWidth = partnerHeaderIcon.width();
			locationAdjust(56, 56, partnerHeaderIconWidth, partnerHeaderIconHeight);
			$('.partnerHeaderIcon').css({
				'margin-left': dw + 7 + 'px',
				'margin-top': dh + 'px'
			});
		};
		
		this.editIcon = function() {
			var editIcon = $('#edit-avatar-right .edit-icon');
			editIcon.each(function(){
				locationAdjust(72, 72, $(this).width(), $(this).height());
				$(this).css({
					'margin-left': dw + 'px',
					'margin-top': dh + 'px'
				});
			});
		}
		this.adjustAll = function() {
			this.partnerAvatar();
			this.partnerHeader();
			this.leftProfileAvatar();
			this.editIcon();
		}
		return this;
	}
	var spriteAvatarIconLocationAdjust = SpriteAvatarIconLocationAdjust();
	spriteAvatarIconLocationAdjust.adjustAll();

	function ChatMessage(sessionId, msgType, content, sendTime, senderId, receiverId, isTimeNode) {
		this.sessionId = sessionId;
		this.msgType = msgType;
		this.sendTime = sendTime;
		this.content = content;
		this.senderId = senderId;
		this.receiverId = receiverId;
		this.isTimeNode = isTimeNode;
	}
	var rightDiv = {};
	rightDiv.chatRecords = new Object();
	rightDiv.adjustMessageInputDivWidth = function() {
		var mediaWidth = $('#media_button_wrapper').outerWidth(true);
		var sendButtonWidth = $('#send-button').outerWidth(true);
		$('#message-input').width($('#right_wrapper').width() - mediaWidth - sendButtonWidth - 30);
		//console.log($('#right_wrapper').width());
	}
	rightDiv.showPartnerInfo = function(partnerBusinessCard, partner) {
		//console.log(partner);
		var partnerAgeGenderWrapper = partnerBusinessCard.find('#partner-age-gender-wrapper');
		if (partner.gender || partner.age || partner.location) {
			partnerAgeGenderWrapper.show();
			if (partner.age) {
				partnerAgeGenderWrapper.find('#partner-age-wrapper').css('display', 'inline-block');
				partnerAgeGenderWrapper.find('#partner-age').text(partner.age);
			} else {
				partnerAgeGenderWrapper.find('#partner-age-wrapper').hide();
			}
			if (partner.gender) {
				partnerAgeGenderWrapper.find('#partner-gender-wrapper').css('display', 'inline-block');
				partnerAgeGenderWrapper.find('#partner-gender-picture').removeClass(partner.gender == 1 ? 'female' : 'male').addClass(partner.gender == 1 ? 'male' : 'female');
				partnerAgeGenderWrapper.find('#partner-gender').text(partner.gender == 1 ? '男' : '女');
			} else {
				partnerAgeGenderWrapper.find('#partner-gender-wrapper').hide();
			}
			if (partner.location) {
				partnerAgeGenderWrapper.find('#partner-location-wrapper').css('display', 'inline-block');
				partnerAgeGenderWrapper.find('#partner-location').text(partner.location);
			} else {
				partnerAgeGenderWrapper.find('#partner-location-wrapper').hide();
			}
		} else {
			partnerAgeGenderWrapper.hide();
		}
		
		var partnerInfoMiddle = partnerBusinessCard.find('#partner-info-middle');
		if (partner.introduction || partner.interests) {
			partnerInfoMiddle.show();
			if (partner.introduction) {
				partnerInfoMiddle.find('#partner-about-me').show();
				partnerInfoMiddle.find('#about-me').text(partner.introduction);
			} else {
				partnerInfoMiddle.find('#partner-about-me').hide();
			}
			
			var partnerTags = partnerInfoMiddle.find('#partner-tags');
			if (partner.interests) {
				partnerTags.show();
				partnerTags.empty();
				for (var i = 0; i < partner.interestsArr.length; i++) {
					partnerTags.append($('<div class="partner_profile_tag"></div>').text(partner.interestsArr[i]));
				}
			} else {
				partnerTags.hide();
			}
		} else {
			partnerInfoMiddle.hide();
		}
	}
	rightDiv.addConvoTimetampDiv = function(chatAreaDiv, time) {
		chatAreaDiv.append($('<div class="convo-timestamp"></div>').append(time + "<div></div>"));
	}
	rightDiv.addMessageDiv = function(chatAreaDiv, msg) {
		//console.log(msg);
		if (msg.sessionId != chatSection.selectedConvo.id)
			return;
		if (msg.isTimeNode)
			this.addConvoTimetampDiv(chatAreaDiv, msg.sendTime);
		var message = "";
		if (msg.msgType == MessageType.TEXT_MSG) {
			var message = $('<div class="message-wrapper clearfix"></div>');
			message.addClass((profile.id == msg.senderId) ? 'mw-right' : 'mw-left');
			var content = $('<div class="message-content"></div>');
			content.text(msg.content);
			message.append(content);
		} else if (msg.msgType == MessageType.IMAGE_MSG) {
			//console.log(msg);
			var message = $("<div class='photo-div'>" +
					"<img src='"+ msg.imagePath + "' class = 'photo-img' />" +
				"</div>");
			message.addClass((profile.id == msg.senderId) ? 'mw-right' : 'mw-left');
		}
		chatAreaDiv.append(message);
	}
	rightDiv.addFriendRequestResultDiv = function(msg, chatAreaDiv) {
		if (chatSection.selectedConvo.id != msg.sessionId)
			return;
		chatAreaDiv = chatAreaDiv || $('#chat-area');
		var msgDiv = '';
		if (msg.content == '0') {
			msgDiv = "<div class='friend-rejected'>" +
						"<span class='friend-rejected-text'>对方拒绝了好友请求</span>" +
					"</div>";
		} else {
			msgDiv = "<div class='friend-accepted'>" +
						"<span class='friend-accepted-text'>" +
							(msg.senderId != profile.id ? "对方" : "你") + "接受了好友请求" +
						"</span>" +
					"</div>";
		}
		chatAreaDiv.append(msgDiv);
	}
	rightDiv.showChatRecord = function(convo) {
		if (!convo.messages) {
			convo.messages = [];
		}
		var chatRecord = convo.messages;
		var chatAreaDiv = $('#chat-area');
		chatAreaDiv.empty();
		for (var i = 0; i < chatRecord.length; i++) {
			var msg = chatRecord[i];
			if (msg.msgType == MessageType.TEXT_MSG || msg.msgType == MessageType.IMAGE_MSG)
				this.addMessageDiv(chatAreaDiv, msg);
			else if (msg.msgType == MessageType.ADD_FRIEND_REQUEST_STATUS) {
				this.addFriendRequestResultDiv(msg, chatAreaDiv);
			}
		}
		
	}
	rightDiv.showChat = function(convo) {
		var partner = convo.partner;
		$('#partner-header').show();
		$('#chat-area').show();
		$('#waiting-tags-screen').hide();
		$('#loading-wrapper').hide();
		
		var teamFreeChatAvatar = $('#teamFreeChatAvatar');
		var partnerHeaderAvatar = $('#partnerHeaderAvatar');
		var partnerNameWrapper = $('#partner-name-wrapper');
		var partnerIconWrapper = $('#partner-icon-wrapper');
		var partnerBusinessCard = $('#partner-business-card');
		partnerNameWrapper.children('#partner-name').text(convo.partnerNickName);
		var partnerNameDivBottom = 0;
		if (convo.partner.id == 'team') {      //如果是与team聊天
			teamFreeChatAvatar.show();
			teamFreeChatAvatar.css('display', 'inline-block');
			partnerNameDivBottom = 10;
			partnerNameWrapper.find('#partner-name-view').hide();
			partnerHeaderAvatar.hide();
			partnerIconWrapper.hide();
			partnerBusinessCard.hide();
		} else {                        //如果与friend或normal聊天
			teamFreeChatAvatar.hide();
			partnerHeaderAvatar.show();
			utils.updateAvatarClass(partnerHeaderAvatar.find('.partnerHeaderColor'),
					utils.getAvatarColorClass(partner.avatarColor, '56'));
			utils.updateAvatarClass(partnerHeaderAvatar.find('.partnerHeaderIcon'),
					utils.getAvatarIconClass(partner.avatarIcon, '56'));
			spriteAvatarIconLocationAdjust.partnerHeader();
			partnerNameWrapper.find('#partner-name-view').show();
			partnerIconWrapper.show();
			
			partnerBusinessCard.show();
			
			var partnerHeaderStarDiv = partnerHeaderAvatar.find('#partnerHeaderStar');
			if (partnerHeaderStarDiv)
				partnerHeaderStarDiv.remove();
			
			var addFriendButton = $('#add-friend-button');
			var newButtonImage = partnerIconWrapper.find('.partner-icon-image');
			var friendButtonImage = addFriendButton.find('.partner-icon-image');
			if (convo.type == Convo.prototype.TYPE_NORMAL) {   //与normal聊天  
				newButtonImage.removeClass('sprite-icon-remove_blue sprite-icon-new_blue').addClass('sprite-icon-next_blue');
				newButtonImage.attr('id', 'end-button-image');
				partnerIconWrapper.find('.label-icon').text('结束聊天');
				
				friendButtonImage.attr('id', 'add-friend-button-image');
				friendButtonImage.removeClass('sprite-icon-my-friends_blue').addClass('sprite-icon-add-friend_blue');
				if (convo.friendRequestSender == convo.userId) {
					addFriendButton.find('.label-icon').text('请求已发送');
				} else
					addFriendButton.find('.label-icon').text('添加朋友');
			} else if (convo.type == Convo.prototype.TYPE_FRIEND) {
				newButtonImage.removeClass('sprite-icon-next_blue sprite-icon-new_blue').addClass('sprite-icon-remove_blue');
				newButtonImage.attr('id', 'remove-button-image');
				partnerIconWrapper.find('.label-icon').text('删除好友');
				
				partnerHeaderAvatar.append('<div id="partnerHeaderStar"></div>');
				
				friendButtonImage.attr('id', 'my-friends-button-image');
				friendButtonImage.addClass('sprite-icon-my-friends_blue').removeClass('sprite-icon-add-friend_blue');
				addFriendButton.find('.label-icon').text('朋友!');
			}
			this.showPartnerInfo(partnerBusinessCard, partner);
		}
		this.showChatRecord(convo);
		partnerNameWrapper.find('#partner-name').css('bottom', partnerNameDivBottom);
		divChatAreaTopAdjust();
		$('#chat-area-wrapper').scrollTop($('#chat-area').height());
	}
	rightDiv.updateOnlineUserCount = function(count) {
		$('#online-count-waiting').find('b').text(count);
	}
	rightDiv.showLoading = function(convo) {
		$('#partner-header').hide();
		$('#partner-business-card').hide();
		$('#chat-area').hide();
		$('#waiting-tags-screen').show();
		$('#loading-wrapper').show();
		$('.loading_ie').hide();
		$('.spinner-wrapper').show();
		divChatAreaTopAdjust();
		
	}
	rightDiv.allowChatFlag = true;
	rightDiv.allowChat = function() {
		if (!this.allowChatFlag) {
			mediaButtonClickRegister();
			sendButtonClickEventRegister();
			$('#message-input').removeAttr("disabled");
			this.allowChatFlag = true;
		}
	}
	rightDiv.notAllowChat = function() {
		$('#media_button').off("click");
		$('#message-input').attr("disabled", "true");
		$('#send-button').off("click");
		this.allowChatFlag = false;
	}
	rightDiv.showRight = function(convoId) {
		var convo = chatSection.selectedConvo;
		if (convo.type == Convo.prototype.TYPE_WAITING) {
			this.showLoading(convo);
			this.notAllowChat();
		} else {
			this.overChatFlag = 0;
			this.showChat(convo);
			this.allowChat();
			if (convo.type == Convo.prototype.TYPE_OVER) {
				rightDiv.overChatFlag = 1;
				rightDiv.overChat();
			}
			if (convo.type != Convo.prototype.TYPE_FRIEND && convo.friendRequestSender == convo.partnerId) {
				$('#friendRequest').show();
			} else if (convo.needEditPartnerNickName) {
				$('#set-friend-input').val(convo.partnerNickName);
				$('#set-friend-name').show();
			} else if (!convo.needEditPartnerNickName) {
				$('#set-friend-name').hide();
				//$('#set-friend-name').show();
			}
		}
	}
	function judgeIsTimeNode(lastMsg, currMsgTime) {
		var lastMsgTime = lastMsg ? lastMsg.sendTime : null;
		console.log(lastMsgTime + "," + currMsgTime);
		if (!lastMsgTime) {
			return 1;
		}
		if (lastMsgTime.length < currMsgTime.length) {
			currMsgTime = currMsgTime.substring("yyyy-MM-dd ".length);
		}
		var i = 0;
		for (i = 0; i < currMsgTime.length; i++) {
			if (currMsgTime.charAt(i) != lastMsgTime.charAt(i))
				break;
		}
		if (currMsgTime.length - i > 2) {
			return 1;
		}
		return 0;
		
	}
	rightDiv.sendTextMessage = function() {
		var messageInput = $('#message-input');
		var message = messageInput.val();
		if (message.length == 0)
			return;
		var date = new Date();
		message = new ChatMessage(chatSection.selectedConvo.id, MessageType.TEXT_MSG, 
				message, date.pattern('yyyy-MM-dd HH:mm:ss'), chatSection.selectedConvo.userId, chatSection.selectedConvo.partner.id);
		message.isTimeNode = judgeIsTimeNode(chatSection.selectedConvo.lastMessage, date.pattern('yyyy-MM-dd HH:mm'));
		//console.log(utils.toJSONString(message));
		ws.send(utils.toJSONString(message));
		message.sendTime = date.pattern("yyyy-MM-dd HH:mm");
		chatSection.newMessageEvent(message);
		messageInput.val('');
	}
	rightDiv.overChatFlag = 0;
	rightDiv.SELF_OVER_CHAT = 1; 
	rightDiv.overChat = function(way) {
		var overChatDiv = $('#new-button');
		if (this.overChatFlag == 0) {
			this.overChatFlag = 1;
			overChatDiv.find('.label-icon').text('确定?');
		} else if (this.overChatFlag == 1) {
			this.overChatFlag = 2;
			var buttonImage = overChatDiv.find('.partner-icon-image');
			buttonImage.removeClass('sprite-icon-next_blue sprite-icon-remove_blue').addClass('sprite-icon-new_blue');
			overChatDiv.find('.label-icon').text('新的');
			var chatArea = $('#chat-area');
			chatArea.empty();
			var date = new Date();
			rightDiv.addConvoTimetampDiv(chatArea, date.pattern('yyyy-MM-dd HH:mm'));
			chatArea.append("<div id = 'disconnectMessage'>" +
						"<span class='disconnectText'>" +
							(way == rightDiv.SELF_OVER_CHAT ? "您已经结束聊天" : "对方已经结束聊天") +
						"</span>" +
					"</div>");
			chatSection.selectedConvo.friendRequestSender = "ban";
			rightDiv.notAllowChat();
			chatSection.removeConvo($('#' + chatSection.selectedConvo.id), false);
		} else {
			this.overChatFlag = 0;
			$('#newTextChat').click();
		}
	}
	$('#set-friend-button').click(function() {
		var friendNameInput = $('#set-friend-input');
		if (friendNameInput.val().length == 0)
			return;
		var convo = chatSection.selectedConvo;
		convo.partnerNickName = friendNameInput.val();
		chatSessionManage.updateFriendNickName(convo.id, convo.userId, convo.partnerNickName);
		var name = convo.partnerNickName;
		$('#partner-header #partner-name').text(name);
		var convoDiv = $('#' + convo.id);
		convoDiv.removeClass('normal').addClass('friends');
		convoDiv.find('.partnerAvatarSmall').after("<div class='conversationStar'></div>");
		var nameSpan = convoDiv.find('.list_name');
		nameSpan.text(name);
		nameSpan.attr('title', '双击编辑');
		nameSpan.on('dblclick', function() {
			chatSection.editFriendsNickName($(this));
		});
		convo.needEditPartnerNickName = false;
		$('#set-friend-name').hide();
	});
	$('#acceptFriend').click(function() {
		$('#friendRequest').hide();
		var convo = chatSection.selectedConvo;
		chatSessionManage.acceptFriend(convo.id, convo.userId, convo.partnerId);
		var msg = new ChatMessage(convo.id, MessageType.ADD_FRIEND_REQUEST_STATUS, '1', '', '', '', 0);
		msg.senderId = convo.userId;
		chatSection.addMessage(msg, convo);
		chatSection.acceptFriend(convo);
	});
	$('#rejectFriend').click(function() {
		$('#friendRequest').hide();
		var convo = chatSection.selectedConvo;
		convo.friendRequestSender = null;
		chatSessionManage.rejectFriend(convo.id, convo.userId, convo.partnerId);
	});
	$('#add-friend-button').click(function() {
		var convo = chatSection.selectedConvo;
		if (!convo.friendRequestSender) {
			$(this).find('.label-icon').text("请求已发送");
			chatSessionManage.addFriend(convo.id, convo.userId, convo.partnerId);
			convo.friendRequestSender = convo.userId;
		}
	});
	$('#new-button').click(function() {
		rightDiv.overChat(rightDiv.SELF_OVER_CHAT);
		if (rightDiv.overChatFlag == 2)
			chatSessionManage.removeConvo(chatSection.selectedConvo.id, profile.id, chatSection.selectedConvo.partnerId);
	});
	var mediaGalleryModal = $('#media-gallery-modal').modal();
	var jcropApi = null;
	mediaGalleryModal.on('hide.bs.modal', function() {
		//console.log('hide.bs.modal');
		$('#image_file').val('');
		if (jcropApi) {
			jcropApi.destroy();
		}
	});
	$('#media-gallery-modal').modal('hide');
	$('#media-gallery-wrapper').click(function() {
		$('#image_file').click();
	});
	function showCoords(c) {
		$('#img_left').val(c.x);
		$('#img_top').val(c.y);
		$('#img_width').val(c.w);
		$('#img_height').val(c.h);
	}
	function imageJcrop() {
		//console.log("ferfer");
		var file = document.getElementById("image_file").files[0];
		//console.log(file.name);
		if (window.FileReader) {
			var fileReader = new FileReader();
			fileReader.onload = function() {
				var jcropImage = $('#image_temp');
				jcropImage.attr({src:this.result, width:650, height:500});
				jcropImage.Jcrop({
					setSelect: [10, 10, 210, 210],
					aspectRatio: 65/50,
					boxWidth: 650,
					boxHeight: 500,
					minSize: [100, 100],
					onChange: showCoords,
					onSelect: showCoords
				}, function() {
					jcropApi = this;
				});
				//$('#send-image').unbind();
				mediaGalleryModal.modal('show');
				$('#media_button').click();  //隐藏上传照片
			}
			fileReader.readAsDataURL(file);
		} else {
			alert('浏览器不支持此功能，请升级浏览器!');
		}
	}
	$('#image_file').on('change', function() {
		imageJcrop();
	});
	$('#send-image').click(function() {
		var file = document.getElementById("image_file").files[0];
		var convo = chatSection.selectedConvo;
		var date = new Date();
		var msg = new ChatMessage(convo.id, MessageType.IMAGE_MSG, "", 
				date.pattern("yyyy-MM-dd HH:mm:ss"), convo.userId, convo.partnerId);
		msg.isTimeNode = judgeIsTimeNode(convo.lastMsgTime, date.pattern("yyyy-MM-dd HH:mm"));
		var imageType = file.name.substring(file.name.indexOf('.'));
		msg.content = Math.uuid() + imageType;
		var form = document.form_send_image;
		var imgCoords = [form.left.value, form.top.value, form.width.value, form.height.value];
		//console.log(imgCoords);
		//var img = dwr.util.getValue("image_file");
		var img = document.getElementById("image_file");
		chatSessionManage.sendImage(img, msg, 
				parseInt(imgCoords[0]), parseInt(imgCoords[1]), parseInt(imgCoords[2]), parseInt(imgCoords[3]), function(data) {
			//console.log("sendImage");
			//这里特别需要注意：当使用ajaxfileupload上传文件时，
			//它会把原来的file元素替换成新的file元素，所以之前绑定的change事件就失效了，需要重新绑定一下 
			$('#image_file').off('change');         
			$('#image_file').on('change', function() {
				imageJcrop();
			});
			console.log(data);
			chatSection.newMessageEvent(data);
		});
		//console.log(imageType);
		$('#media-gallery-modal').modal('hide');
		console.log(msg.content);
	});
	function mediaButtonClickRegister() {
		$('#media_button').on("click" , function() {
			var mediaMenu = $('#media-menu');
			if (mediaMenu.is(':hidden')) {
				mediaMenu.show();
				$('body').mousedown(function(event) {
					var target = $(event.target);
					if (target.attr('id') == 'media-menu' || target.attr('id') == 'media_button'
						|| target.parents('#media-menu').attr('id') == 'media-menu') {
						return;
					}
					$('#media_button').click();
				});
				$(this).removeClass('plus').addClass('exit');
			} else {
				$('body').unbind('mousedown');
				mediaMenu.hide();
				$(this).removeClass('exit').addClass('plus');
			}
		});
	}
	mediaButtonClickRegister();
	
	$('#media-menu').focusout(function() {
		if (!$(this).is(':hidden')) {
			$(this).hide();
			$('#media_button').removeClass('exit').addClass('plus');
		}
	});
	$('#message-input').bind('input', function() {
		
	});
	$('#message-input').keydown(function(event) {
		if (event.which == 13) {
			rightDiv.sendTextMessage();
		}
	});
	function sendButtonClickEventRegister() {
		$('#send-button').on("click", function() {
			rightDiv.sendTextMessage();
		});
	}
	sendButtonClickEventRegister();
	
	//pageInit.addInitFun(rightDiv.initChatRecords);
	windowResize.add(rightDiv.adjustMessageInputDivWidth);
	
	$('#newTextChat').click(function() {
		chatSection.createNewWaitingDiv();
	});

	
	
	var editProfile = {
		toggleProfile:function() {
			$('#edit_profile_header_main').toggle();
			$('#new-button-wrapper').toggle();
			$('#left_profile_display_input').toggle();
			$('#left_profile_display').toggle();
			$('#toggle-profile').toggle();
			$('#profile_chat_section').toggle();
			$('#edit-profile-section').toggle();
		},
		adjustEditProfileSectionHeight:function() {
			var bodyHeight = $('body').height();
			var editProfileHeaderHeight = $('#edit_profile_header_main').outerHeight(true);
			var leftProfileTopHeight = $('#left_profile_top').outerHeight(true);
			$('#edit-profile-section').height(bodyHeight - editProfileHeaderHeight - leftProfileTopHeight - 15);
		},
		updateProfileAvatarColor: function(profileAvatar, colorClass) {
			//alert(colorClass);
			utils.updateAvatarClass(profileAvatar, colorClass.replace("72", "56")); //更新用户头像的颜色
			profile.avatarColor = utils.getAvatarColor(colorClass);     
			//更新可选头像icon的颜色
			utils.updateAvatarClass($('#edit-avatar-right .' + utils.getAvatarIconClass(profile.avatarIcon, 72)).prev(), colorClass);
		},
		editAvatarColorCheck: function(obj) {
			obj.before($('.edit-color-checkmark').remove());
			this.updateProfileAvatarColor($('#left_profile_avatar_wrapper .left_profile_color'), utils.getSpriteAvatarClass(obj));
		},
		updateProfileAvatarIcon: function(profileAvatar, iconClass) {
			utils.updateAvatarClass(profileAvatar, iconClass.replace("72", "56")); //更新用户头像icon
			profile.avatarIcon = utils.getAvatarIcon(iconClass);
			spriteAvatarIconLocationAdjust.leftProfileAvatar();
		},
		editAvatarIconCheck: function(avatarColorDiv, avatarIconDiv, avatarIconName) {
			try {
				//将之前被选择的icon颜色变成灰色
				utils.updateAvatarClass($('#edit-avatar-right .' + utils.getAvatarColorClass(profile.avatarColor, 72)), utils.getAvatarColorClass('Grey', 72));
				//将现在被选择的icon颜色变成已经选定的颜色
				utils.updateAvatarClass(avatarColorDiv, utils.getAvatarColorClass(profile.avatarColor, 72));
				this.updateProfileAvatarIcon($('#left_profile_avatar_wrapper .left_profile_avatar'), utils.getSpriteAvatarClass(avatarIconDiv));
				profile.avatarIconName = avatarIconName;
			} catch(e) {
				alert(e);
			}
			
		},
		updateNickName: function() {
			profile.nickName = $('#left_profile_display_input').val();
			var nickName = profile.nickName;
			if (nickName.length == 0) {
				nickName = profile.avatarIconName;
			}
			$('#left_profile_display').text(nickName);
		},
		validateAge: function() {
			var profileErrorMessageDiv = $('#profile-error-message');
			var profileAgeDiv = $('#profile-age');
			profileAgeDiv.removeClass("red yellow");
			profileAgeDiv.attr('placeholder', 'Age');
			profileErrorMessageDiv.hide();
			var ageStr = profileAgeDiv.val();
			var ageInt = parseInt(ageStr);
			if (ageStr.length == 0)
				return true;
			if (ageStr.length != 0 && isNaN(ageInt)) {
				profileAgeDiv.addClass('yellow');
				profileErrorMessageDiv.text('请输入正确的年龄格式');
				profileErrorMessageDiv.show();
				return false;
			}
			if (ageStr.length != 0 && ageInt < 10) {
				profileAgeDiv.addClass('red yellow');
				profileAgeDiv.attr('placeholder', '>10');
				profileAgeDiv.val('');
				profileErrorMessageDiv.text('年龄必须大于或等于10');
				profileErrorMessageDiv.show();
				return false;
			}
			profile.age = ageInt;
			return true;
		},
		validate: function() {
			var result = this.validateAge();
			return result;
		},
		setLocation : function() {
			$.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js',
					function(_result) {
						if (remote_ip_info.ret == '1') {
							profile.location = remote_ip_info.province + "-" + remote_ip_info.city;
							console.log(profile.location);
//							alert('国家：' + remote_ip_info.country + '<BR>省：'
//								+ remote_ip_info.province + '<BR>市：'
//								+ remote_ip_info.city + '<BR>区：'
//								+ remote_ip_info.district + '<BR>ISP：'
//								+ remote_ip_info.isp + '<BR>类型：'
//								+ remote_ip_info.type + '<BR>其他：'
//								+ remote_ip_info.desc);
						} else {
							profile.location = "";
						}
			});
			return "";
		},
		editLocation: function() {
			var locationIconDiv = $('#profile-location-icon');
			var locationText = $('#profile-location-text');
			if (locationIconDiv.hasClass('location-icon-on')) {
				locationIconDiv.removeClass();
				locationIconDiv.addClass('location-icon-off');
				locationText.removeClass();
				locationText.addClass('location-text-off');
				locationText.text('OFF');
			} else {
				locationIconDiv.removeClass();
				locationIconDiv.addClass('location-icon-on');
				locationText.removeClass();
				locationText.addClass('location-text-on');
				locationText.text('ON');
			}
			
			if (locationText.text() == 'ON') {
				this.setLocation();
			} else {
				profile.location = "";
			}
		},
		toggleProfileTagsView:function() {
			$('#edit_profile_header_main').toggle();
			$('#left_profile_wrapper').toggle();
			$('#edit_profile_tags_view').toggle();
		},
		containTag: function(tags, tagName) {
			var contain = false;
			tags.each(function() {
				if ($(this).text() == tagName) {
					contain = true;
					return false;
				}
			});
			return contain;
		},
		allTagsIndex : [],
		initAllTagsIndex: function() {
			$('#edit_profile_tags_list .profile_tag_element').each(function() {
				editProfile.allTagsIndex[$(this).text()] = $(this).index();
			});
			/*for (var o in this.allTagsIndex) {
				alert(o);
			}*/
			
		},
		addInterest: function(inter) {
			inter = inter.substring(1);
			profile.interestsArr.push(inter);
		},
		interestsTagNum:-1, 
		addTagToCur: function(tagText) {
			if (this.interestsTagNum >= 5) {
				$('#edit_profile_tags_input').addClass('red').attr('placeholder', '最多只能有五个标签').val('');
				return false;
			}
			if (!this.containTag($('#edit_profile_tags_current .left_profile_tag_text'), tagText)) {
				newTag = $('<div class="left_profile_tag"></div>');
				newTag.append($('<span class="left_profile_tag_text"></span>').text(tagText));
				newTag.append($('<span class="left_profile_tag_icon"></span>'));
				newTag.click(function() {
					editProfile.moveTag($(this), true);
				});
				$('#edit_profile_tags_current').append(newTag);
				 
				this.interestsTagNum++;
				//this.addInterest(tagText);
				return true;
			}
		},
		interests:[],
		removeInterest: function(inter) {
			inter = inter.substring(1);
			var intersArr = profile.interestsArr;
			utils.removeArrElement(intersArr, '',intersArr.indexOf(inter), 1);
			var inters = intersArr.length != 0 ? intersArr[0] : '';
			for (var i = 1; i < intersArr.length; i++) {
				inters += ',' + intersArr[i];
			}
			profile.interests = inters;
			profile.interestsArr = intersArr;
		},
		moveTag: function(tag, selected) { //selected参数代表准备移除的标签是从那什么地方移除
			var newTag;
			var tagText;
			if (selected) {  //从#edit_profile_tags_current中移除
				tagText = tag.find('.left_profile_tag_text').text();
				$('#edit_profile_tags_list .profile_tag_element').each(function() {
					if ($(this).text() == tagText) {   //当找到一样的index时返回
						$(this).show();
						return false;
					}
				});
				//this.removeInterest(tagText);
				tag.remove();
				this.interestsTagNum--;
				if (this.interestsTagNum < 5) {
					$('#edit_profile_tags_input').removeClass('red').attr('placeholder', '在此输入标签');
				}
			} else {
				tagText = tag.text();
				if (this.addTagToCur(tagText))
					tag.hide();
				//this.interests[tagText] = this.allTagsIndex[tagText];
				//this.allTagsIndex[tagText] = -1;
			}
			
		},
		updateProfileTag : function() {
			var intersArr = [];
			$('#edit_profile_tags_current .left_profile_tag_text').each(function() {
				intersArr.push($(this).text().substring(1));
			});
			var inters = intersArr.length != 0 ? intersArr[0] : '';
			for (var i = 1; i < intersArr.length; i++) {
				inters += ',' + intersArr[i];
			}
			profile.interests = inters;
			profile.interestsArr = intersArr;
		},
		bindTagClickListener: function() {
			$('#edit_profile_tags_current .left_profile_tag').unbind().click(function() {
				editProfile.moveTag($(this), true);
			});
			$('#edit_profile_tags_list li').unbind().click(function() {
				editProfile.moveTag($(this), false);
			});
		},
		editProfileClick: function() {
			editProfile.toggleProfile();
			$('#left_profile_avatar_wrapper,#left_profile_top_right').unbind('click', this.editProfileClick);
			if (profile.registered == 1) {
				$('#left_profile_username').on('click', function(){
					showEditUsernameModal();
				});
			}
			$('#left_profile_avatar_wrapper').click(function(){
				var editAvatarModal = $('#edit-avatar-modal');
				editAvatarModal.toggle();
				$('#edit-avatar-close-span').click(function(){
					editAvatarModal.hide();
				});
				var editAvatarLeft = $('#edit-avatar-left');
				var editAvatarRight = $('#edit-avatar-right');
				var editColorHeader = $('#edit-color-header');
				var editIconHeader = $('#edit-icon-header');
				var activeAvatarHeader = 'active_avatar_header';
				//头像背景color或头像icon的div切换
				editColorHeader.click(function(){
					editIconHeader.removeClass(activeAvatarHeader);
					editAvatarRight.hide();
					editAvatarLeft.show();
					$(this).addClass(activeAvatarHeader);
				});
				editIconHeader.click(function(){
					editColorHeader.removeClass(activeAvatarHeader);
					editAvatarLeft.hide();
					editAvatarRight.show();
					$(this).addClass(activeAvatarHeader);
				});
				$('.edit-color').click(function() {
					editProfile.editAvatarColorCheck($(this));
				});
				$('.edit-icon-div').click(function() {
					editProfile.editAvatarIconCheck($(this).find('.edit-icon-color'), $(this).find('.edit-icon'), $(this).find('.edit-icon-title').text());
				});
			});
			
			var editProfileMale = $('#edit_profile_male');
			var editProfileFemale = $('#edit_profile_female');
			var activeGender = "edit_profile_gender_active";
			var genderText = ".edit_profile_gender_text";
			editProfileMale.click(function() {
				profile.gender = 1;
				editProfileFemale.find(genderText).removeClass(activeGender);
				editProfileMale.find(genderText).addClass(activeGender);
			});
			editProfileFemale.click(function() {
				profile.gender = 2;
				editProfileMale.find(genderText).removeClass(activeGender);
				editProfileFemale.find(genderText).addClass(activeGender);
			});
		},
			
	};
	$('#logout-button').click(function() {
		userManage.logout(function() {
			 window.onbeforeunload = null;
			location.reload();
		});
	});
	$('#edit_profile_tags_input').keydown(function(event) {
		if (event.which == 13) {
			var tag = $(this).val();
			if (tag.length == 0) {
				return;
			}
			if (editProfile.addTagToCur('#' + tag)) 
				$(this).val('');
		}
	});
	$('#edit_profile_tags_input').bind('input propertychange', function() {
		var tag = '#' + $(this).val();
		var patt = new RegExp('^' + tag, "i");
		$('#edit_profile_tags_list li').each(function() {
			var eachTag = $(this).text();
			if (tag.length != 0 && eachTag.search(patt) == -1) {
				$(this).hide();
			} else if (tag.length == 0 || eachTag.search(patt) != -1) {
				function equal(inter) {
					return inter == eachTag;
				}
				if (!profile.interestsArr.some(equal)) {
					$(this).show();
				}
			}
			
		});
	}); 
	pageInit.addInitFun(editProfile.initAllTagsIndex);
	pageInit.addInitFun(editProfile.bindTagClickListener);
	$('#edit_profile_tags_back').click(function() {
		editProfile.updateProfileTag();
		editProfile.toggleProfileTagsView();
		var leftProfileTags = $("#left_profile_bottom");
		leftProfileTags.children('.left_profile_tag').remove();
		for (var i = 0; i < profile.interestsArr.length; i++) {
			var tag = $('<div class="left_profile_tag"></div>');
			tag.append('<span class="left_profile_tag_text"></span>').text('#' + profile.interestsArr[i]);
			leftProfileTags.append(tag);
		}
		
	});
	$('#left_profile_bottom').click(function() {
		editProfile.toggleProfileTagsView();
	});
	$('#profile-location-wrapper').click(function() {
		editProfile.editLocation();
	});
	$('#profile_about_title_wrapper').click(function() {
		$('#left_profile_about').toggle();
		$('#left_profile_about_textbox').toggle(0, function() {
			profile.introduction = $(this).val();
			$('#left_profile_about').text(profile.introduction);
		});
	});
	
	$('#toggle-profile,#left_profile_avatar_wrapper,#left_profile_top_right').bind("click", editProfile.editProfileClick);
	$('#edit_profile_main_back').click(function(){
		if (!editProfile.validate()) {
			return;
		}
		//console.log(profile);
		editProfile.toggleProfile();
		editProfile.updateNickName();
		//delete windowResize.adjustEditProfileSectionHeight;
		//windowResize.remove();
		$('#edit-avatar-modal').hide();
		$('#left_profile_avatar_wrapper').unbind("click");
		$('#left_profile_avatar_wrapper,#left_profile_top_right').bind('click', editProfile.editProfileClick);
		$('#left_profile_username').off('click');
		userManage.updateUserInfo(profile);
		adjustConversationSidebarHeight();
	});
	
	windowResize.add(editProfile.adjustEditProfileSectionHeight);
	
	windowResize.resize();
	$(window).resize(function() {
		windowResize.resize();
	});
	
	
	pageInit.init();
	
	 window.onbeforeunload = userLeaveHandler;  
	 //window.onunload = onunload_handler;  
	 function userLeaveHandler() {
		ajaxUtils.setAsync(false);
		userManage.leave();
		ajaxUtils.setAsync(true);
	 }  
	 
});

ajaxUtils.setErrorHandler(function(error) {
	//alert("fdewf");
	if (error == 'NetworkError') {
		return;
	}
	alert(error);
});

//解决DWR上传文件的问题
//dwr.engine.transport.iframe.loadingComplete = function(batchId) {
//	var isChrome = (/\bchrome\b/).test(navigator.userAgent.toLowerCase());
//	var batch = dwr.engine._batches[batchId];
//	if(!isChrome && batch)
//		dwr.engine.batch.validate(batch);
//}


